package io.noties.markwon.plugin.highlight

import io.noties.markwon.plugin.highlight.parser.HighlightDelimiterProcessor
import org.commonmark.Extension
import org.commonmark.parser.Parser
import org.commonmark.parser.Parser.ParserExtension
import org.commonmark.renderer.html.HtmlRenderer
import org.commonmark.renderer.html.HtmlRenderer.HtmlRendererExtension
import org.commonmark.renderer.text.TextContentRenderer
import org.commonmark.renderer.text.TextContentRenderer.TextContentRendererExtension

class HighlightExtension private constructor(builder: Builder) :
    ParserExtension, HtmlRendererExtension, TextContentRendererExtension {
    private val requireTwoTildes: Boolean

    init {
        requireTwoTildes = builder.requireTwoTildes
    }

    override fun extend(parserBuilder: Parser.Builder) {
        parserBuilder.customDelimiterProcessor(HighlightDelimiterProcessor(requireTwoTildes))
    }

    /*override fun extend(rendererBuilder: HtmlRenderer.Builder) {
        rendererBuilder.nodeRendererFactory { context -> StrikethroughHtmlNodeRenderer(context) }
    }

    override fun extend(rendererBuilder: TextContentRenderer.Builder) {
        rendererBuilder.nodeRendererFactory { context ->
            StrikethroughTextContentNodeRenderer(
                context
            )
        }
    }*/

    override fun extend(rendererBuilder: HtmlRenderer.Builder?) {
    }

    override fun extend(rendererBuilder: TextContentRenderer.Builder?) {
    }

    class Builder {
        var requireTwoTildes = true

        /**
         * @param requireTwoTildes Whether two tilde characters (`~~`) are required for strikethrough or whether
         * one is also enough. Default is `false`; both a single tilde and two tildes can be used for strikethrough.
         * @return `this`
         */
        fun requireTwoTildes(requireTwoTildes: Boolean): Builder {
            this.requireTwoTildes = requireTwoTildes
            return this
        }

        /**
         * @return a configured extension
         */
        fun build(): Extension {
            return HighlightExtension(this)
        }
    }

    companion object {
        /**
         * @return the extension with default options
         */
        fun create(): Extension {
            return builder().build()
        }

        /**
         * @return a builder to configure the behavior of the extension
         */
        fun builder(): Builder {
            return Builder()
        }
    }
}